﻿using System;
using System.IO;
using UnityEditor;
using winS.Cryptography;
using winS.Unity;

namespace winS.UnityEditor
{
    public static class Editor
    {
        public static event Action onExitPlayMode;
        public static event Action onEnterPlayMode;

        /// <summary>
        /// path of current project.
        /// </summary>
        public static readonly string projectFolderPath = Directory.GetCurrentDirectory().Replace('\\', '/');
        /// <summary>
        /// "Packages" Folder path of current Project.
        /// </summary>
        public static readonly string packagesFolderPath = $"{projectFolderPath}/Packages";
        /// <summary>
        /// Directory of current project data.
        /// </summary>
        public static readonly string projectDataDirectory = $"{projectFolderPath}/ProjectData";
        /// <summary>
        /// Folder name of current Project.
        /// </summary>
        public static readonly string projectFolderName = Path.GetFileName(projectFolderPath);
        /// <summary>
        /// MD5 of current project.
        /// </summary>
        public static readonly string projectMD5 = OneWayEncryption.CreateMD5FromText(projectFolderPath);
        /// <summary>
        /// Directory of all project data (Local).
        /// </summary>
        public static readonly string editorDataLocalDirectory = $"{Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData).Replace('\\', '/')}/{nameof(winS)}/{nameof(UnityEditor)}";
        /// <summary>
        /// Directory of current project data (Local).
        /// </summary>
        public static readonly string projectDataLocalDirectory = $"{editorDataLocalDirectory}/{projectFolderName}({projectMD5})";
        /// <summary>
        /// Directory of editor window data for current project (Local).
        /// </summary>
        public static readonly string projectEditorWindowDataLocalDirectory = $"{projectDataLocalDirectory}/EditorWindowData/";

        private static readonly EditorModuleManager editorModuleManager = new EditorModuleManager();

        static Editor()
        {
            EditorApplication.playModeStateChanged += OnPlayModeStateChanged;
        }

        public static T GetModule<T>() where T : Module
        {
            return editorModuleManager.GetModule<T>();
        }

        private static void OnPlayModeStateChanged(PlayModeStateChange playModeStateChange)
        {
            switch (playModeStateChange)
            {
                case PlayModeStateChange.EnteredEditMode: onExitPlayMode?.Invoke(); return;
                case PlayModeStateChange.EnteredPlayMode: onEnterPlayMode?.Invoke(); return;
                default: return;
            }
        }
    }
}